package com.farm.web.init.commons;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.farm.core.time.TimeTool;

/**
 * 编码免费版的信息key
 * 
 * @author macpl
 *
 */
public class FreeVersionInfoUtils {
	public static CompanyUser decode(String key) {
		CompanyUser info = new CompanyUser();
		String id = UUID.randomUUID().toString().replaceAll("-", "");
		if (StringUtils.isNotBlank(key) && key.length() > 16) {
			info.setDaypv(Integer.valueOf(key.substring(0, 5)));
			info.setDocnum(Integer.valueOf(key.substring(10, 15)));
			try {
				info.setEname(new String(Base64.decodeBase64(key.substring(15)), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
			info.setOvertime(TimeTool.getTimeDate12());
			info.setPersonnum(Integer.valueOf(key.substring(5, 10)));
			info.setId(id);
		} else {
			throw new RuntimeException("the key(" + key + ") format exception!");
		}
		return info;
	}

	public static String encode(int pv, int personnum, int docnum, String companyName) {
		// System.out.println("paras:" + pv + "|" + personnum + "|" + docnum +
		// "|" + companyName);
		String pvs = "00000" + Integer.toString(pv);
		pvs = pvs.substring(pvs.length() - 5);
		String personnums = "00000" + Integer.toString(personnum);
		personnums = personnums.substring(personnums.length() - 5);
		String docnums = "00000" + Integer.toString(docnum);
		docnums = docnums.substring(docnums.length() - 5);
		String encode = null;
		try {
			encode = pvs + personnums + docnums + Base64.encodeBase64String(companyName.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			encode = pvs + personnums + docnums + "NONE";
		}
		// System.out.println("encode:" + encode);
		// System.out.println("decode:" + decode(encode).getEname());
		return encode;
	}

	public static void main(String[] args) {
		String key = encode(0, 6, 7, "wcp知识分享平台wcp知识分享平台");
		CompanyUser info = decode(key);
		System.out
				.println(info.getDaypv() + "|" + info.getPersonnum() + "|" + info.getDocnum() + "|" + info.getEname());
	}
}
